package com.btr.ivle.backgroud;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.widget.Toast;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;

public class DownloadFilesTask extends AsyncTask<String, Integer, Void>{
	
	private Context context;
	private ProgressDialog mProgressDialog;
	private String folderName;
	
	public DownloadFilesTask(Context context){
		this.context = context;
		mProgressDialog = new ProgressDialog(context);
		mProgressDialog.setMessage("Downloading...");
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	}

	protected Void doInBackground(String... texts) {
		try {
			String ID = texts[0];
			folderName = texts[4].replaceAll("[^a-zA-Z0-9]","");
			URL url = new URL("https://ivle.nus.edu.sg/api/downloadfile.ashx?APIKey=" +
					context.getString(R.string.IVLE_API_KEY) + "&AuthToken=" + IVLEToken.getToken() + "&ID="
    				+ ID + "&target=workbin");
			URLConnection connection = url.openConnection();
			connection.connect();
            int fileLength = Integer.valueOf(texts[2]);
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/IVLE/" + folderName+ "/" + texts[1]);
            
            byte data[] = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int) (total * 100 / fileLength));
                
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();
            
//            DatabaseWorkbin db = new DatabaseWorkbin(context ,IVLEToken.getUserID() + "_Workbin",
//            		null, context.getResources().getInteger(R.integer.DBVersion));
//            String table = IVLEToken.getUserID()+"_Workbin"; 
//            String[] columns = new  String[] {db.isDownloaded}; 
//            String selection = db.ID + "=?";
//    		String[] selectionArgs = new  String[] {ID};
//            Cursor c = db.getReadableDatabase().query(table, columns, 
//            		selection, selectionArgs, null, null, null, null);
//            c.moveToFirst();
//            int isDownloaded = c.getInt(0);
            
//            ContentValues values = new ContentValues();
//            values.put(db.isDownloaded, true);
//            String selection = db.ID + "=?";
//            String[] selectionArgs = new  String[] {ID};
//    		db.getWritableDatabase().update(table, values, selection, selectionArgs);
//    		db.getWritableDatabase().close();
//    		db.close();
    		
//    		if(isDownloaded==0){
//	    		DatabaseModuleItem dbModuleItem = new DatabaseModuleItem(context,IVLEToken.getUserID()+"_ModuleItem",
//	    				null,context.getResources().getInteger(R.integer.DBVersion));
//	    		table = IVLEToken.getUserID()+"_ModuleItem";
//	    		columns = new  String[] {dbModuleItem.colBadgeTool};
//	    		selection = dbModuleItem.colID + "=?";
//	    		selectionArgs = new  String[] {texts[3]};
//	    		c = db.getReadableDatabase().query(table, columns, 
//	            		selection, selectionArgs, null, null, null, null);
//	    		c.moveToFirst();
//	    		int badge = c.getInt(0)-1;
//	    		values = new ContentValues();
//	    		values.put(dbModuleItem.colBadgeTool, badge);
//	    		selection = dbModuleItem.colBadgeTool + "=?";
//	    		selectionArgs = new  String[] {texts[3]};
//	    		dbModuleItem.getWritableDatabase().update(table, values, selection, selectionArgs);
//	    		dbModuleItem.getWritableDatabase().close();
//	    		dbModuleItem.close();
//    		}
    		
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.show();
    }
	
	protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        mProgressDialog.setProgress(progress[0]);
    }
	
    @SuppressWarnings("unchecked")
	protected void onPostExecute(Void result) {
    	mProgressDialog.dismiss();
    	Toast.makeText(context, "File is downloaded to sdcard/IVLE/" + folderName + "/", Toast.LENGTH_LONG).show();
    	AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete("");
    }
}
